Analysis

Today is

## [1] "Mon Nov 16 16:10:23 2020"

This week we use the Boston data from the MASS package. The data have 14 variables and 506 observartions for each variable. The variables are either numerical or integers.

# Package
library(MASS)
data(Boston)
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston)
## [1] 506  14
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

Namely, the variables are

The correlation matrix can be illustrated by using corrplot package as follows

library(corrplot)
## corrplot 0.84 loaded
corr_matrix<-cor(Boston)
corrplot(corr_matrix)

That is, there is a a significant positive correlation between crim, rad, tax and lsat. On the other hand, the weighted mean of distances to five Boston employment centres, dis, has negative correlation with indus, nox, and age.

However, since the crime rate seems to be the variable in interest, let us illustrate it by some graphics.

require(ggplot2)
## Loading required package: ggplot2
require(plotly)
## Loading required package: plotly
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(data = Boston, x = ~crim, type = "histogram")
## Warning: `arrange_()` is deprecated as of dplyr 0.7.0.
## Please use `arrange()` instead.
## See vignette('programming') for more help
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_warnings()` to see where this warning was generated.
plot_ly(data = Boston, x = ~rad, y = ~crim)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
plot_ly(data = Boston, x = ~tax, y = ~crim)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
plot_ly(data = Boston, x = ~lstat, y = ~crim)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

Next we standardize the dataset and print out summaries of the scaled data.

scaled.Boston <- data.frame(scale(Boston))

Now all variables have mean of \(0\) and variance \(1\). For instance, now the plot of crim and lstat is the following.

plot_ly(data = scaled.Boston, x = ~lstat, y = ~crim)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

Next we divide crim in 5 categories based on the 20/%-quantiles.

library(gtools)
q.crim <- quantcut(scaled.Boston$crim,q = 5)
summary(q.crim)
## [-0.419,-0.413] (-0.413,-0.403] (-0.403,-0.356]  (-0.356,0.229]    (0.229,9.92] 
##             102             101             101             101             101
scaled.Boston$crim <- q.crim

We divide the dataset into train and test sets, so that 80/% of the data belongs to the train set.

sample <- sample.int(n = nrow(scaled.Boston), size = floor(.8*nrow(scaled.Boston)), replace = F)
train <- scaled.Boston[sample, ]
test  <- scaled.Boston[-sample, ]

The linear discriminant analysis:

# MASS and train are available

# linear discriminant analysis
lda.fit <- lda(crim~., data = train)

# print the lda.fit object
lda.fit
## Call:
## lda(crim ~ ., data = train)
## 
## Prior probabilities of groups:
## [-0.419,-0.413] (-0.413,-0.403] (-0.403,-0.356]  (-0.356,0.229]    (0.229,9.92] 
##       0.2029703       0.1856436       0.2029703       0.2079208       0.2004950 
## 
## Group means:
##                          zn      indus        chas        nox         rm
## [-0.419,-0.413]  1.27490554 -0.9751789 -0.12828882 -0.9281439  0.4340736
## (-0.413,-0.403]  0.02499867 -0.4043881 -0.06235039 -0.6386194  0.1513090
## (-0.403,-0.356] -0.28383523 -0.1346476  0.06376485 -0.2833197 -0.0263999
## (-0.356,0.229]  -0.43619598  0.6086224  0.29011382  0.8406458 -0.1666777
## (0.229,9.92]    -0.48724019  1.0149946 -0.12651054  1.0304289 -0.3523930
##                         age         dis        rad        tax     ptratio
## [-0.419,-0.413] -0.92099289  1.06363342 -0.6905527 -0.7577000 -0.44587251
## (-0.413,-0.403] -0.48272768  0.32814709 -0.5944550 -0.5800334 -0.24551823
## (-0.403,-0.356] -0.01184552  0.07192695 -0.5084787 -0.4684824  0.04307124
## (-0.356,0.229]   0.62114849 -0.53919931  0.1529236  0.2838204 -0.09218764
## (0.229,9.92]     0.82981801 -0.87828297  1.6596029  1.5294129  0.80577843
##                      black      lstat        medv
## [-0.419,-0.413]  0.3838353 -0.7871536  0.45707638
## (-0.413,-0.403]  0.3598505 -0.4392806  0.27913065
## (-0.403,-0.356]  0.2980892  0.0344603  0.07665441
## (-0.356,0.229]  -0.1400523  0.2045559 -0.06155630
## (0.229,9.92]    -0.8294040  0.9356977 -0.80534920
## 
## Coefficients of linear discriminants:
##                 LD1          LD2          LD3         LD4
## zn      -0.10444826  1.086229411  0.772871173 -0.34842203
## indus    0.05732268 -0.231555814 -0.008189145  0.25768166
## chas    -0.07742623 -0.068702372  0.047144473 -0.10539053
## nox      0.37351480 -0.610843610  1.656097338 -0.42063611
## rm       0.04264437  0.191891654 -0.312518370 -0.23355693
## age      0.24457759 -0.094276812  0.407446972 -0.40276985
## dis     -0.07442784 -0.547893141  0.554907062 -0.56607583
## rad      1.54139735  1.213087688 -0.334272166  0.20471225
## tax      0.12024815 -0.466080242 -0.163815930  0.42828018
## ptratio -0.06507714  0.004094212  0.123961196 -0.84401810
## black   -0.19666704 -0.023069739 -0.090217162 -0.03646267
## lstat    0.24581800 -0.208931456 -0.772083666 -1.18540657
## medv     0.00516920 -0.709983352  0.166682178 -0.61028042
## 
## Proportion of trace:
##    LD1    LD2    LD3    LD4 
## 0.8423 0.1035 0.0477 0.0065
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crim)

# plot the lda results
plot(lda.fit, dimen = 2)
lda.arrows(lda.fit, myscale = 1)

Next we cross tabulate the results with the crime categories from the test set.

# lda.fit, correct_classes and test are available
correct_classes <- test$crim

# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
##                  predicted
## correct           [-0.419,-0.413] (-0.413,-0.403] (-0.403,-0.356]
##   [-0.419,-0.413]               7               7               6
##   (-0.413,-0.403]               9              10               6
##   (-0.403,-0.356]               0               5              13
##   (-0.356,0.229]                0               1               5
##   (0.229,9.92]                  0               0               0
##                  predicted
## correct           (-0.356,0.229] (0.229,9.92]
##   [-0.419,-0.413]              0            0
##   (-0.413,-0.403]              1            0
##   (-0.403,-0.356]              1            0
##   (-0.356,0.229]               7            4
##   (0.229,9.92]                 1           19

Let us next reload the Boston dataset and standardize it. Then we calculate the distances between the observations.

# load MASS and Boston
library(MASS)
data('Boston')

# standardization
Boston <- scale(Boston)

# euclidean distance matrix
dist_eu <- dist(Boston)

# look at the summary of the distances
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970
# manhattan distance matrix
dist_man <- dist(Boston, method = "manhattan")

# look at the summary of the distances
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.4832 12.6090 13.5488 17.7568 48.8618

One way to determine the number of clusters is to look at how the total of within cluster sum of squares (WCSS) behaves when the number of cluster changes. The optimal number of clusters is when the value of total WCSS changes radically. In this case, two clusters would seem optimal.

# MASS, ggplot2 and Boston dataset are available
set.seed(123)

# determine the number of clusters
k_max <- 10

# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(Boston, k)$tot.withinss})

# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')

# k-means clustering
km <-kmeans(Boston, centers = 2)

# plot the Boston dataset with clusters
pairs(Boston, col = km$cluster)